package vn.personal.anhht.bloback12.block;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import vn.personal.anhht.bloback12.activity.NotificationActivity;
import vn.personal.anhht.bloback12.activity.R;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseAdapter;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseFilterAdapter;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseSMSAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import vn.personal.anhht.bloback12.util.UtilMethods;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver {

	private Context context = null;
	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	Resources res;
	@Override
	public void onReceive(Context context, Intent intent) {
		res = context.getResources();
		this.context = context.getApplicationContext();
		boolean turnBlock = context.getSharedPreferences(
                Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getBoolean(
                        res.getString(R.string.sms_pref_turn_key), true);
		String typeBlock = context.getSharedPreferences(
		        Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
		                res.getString(R.string.sms_pref_mode_block_key), "");
		String typeInform = context.getSharedPreferences(
                Constants.SETTINGS_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
                        res.getString(R.string.sms_pref_mode_inform_key), "");
		if (turnBlock) {
			if (intent.getAction().equals(ACTION)) {
				// StringBuilder sb = new StringBuilder();
				// the message is hiding in intent's extras
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					Object[] pdus = (Object[]) bundle.get("pdus");
					SmsMessage[] messages = new SmsMessage[pdus.length];
					for (int i = 0; i < pdus.length; i++) {
						messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					}
					for (SmsMessage msg : messages) {
						String phone = msg.getDisplayOriginatingAddress();
						String content = msg.getDisplayMessageBody();
						if("blacklist".equals(typeBlock)){
							if (checkBlockSMS(phone)) {
								this.abortBroadcast();
								saveSMS(phone,
										String.valueOf(UtilMethods.dateToMiliSeconds(new Date())),
										content, "");
								if ("showsms".equals(typeInform)) {
								    sendNotification(phone);
                                }
							}
						} else if("ban".equals(typeBlock)){
						    if (filterSMS(content)) {
                                this.abortBroadcast();
                                saveSMS(phone,
                                        String.valueOf(UtilMethods.dateToMiliSeconds(new Date())),
                                        content, "");
                                if ("showsms".equals(typeInform)) {
                                    sendNotification(phone);
                                }
                            }
						} else if("whilelist".equals(typeBlock)){
                            if (checkNotWhiteSMS(phone)) {
                                this.abortBroadcast();
                                saveSMS(phone,
                                        String.valueOf(UtilMethods.dateToMiliSeconds(new Date())),
                                        content, "");
                                if ("showsms".equals(typeInform)) {
                                    sendNotification(phone);
                                }
                            }
                        } else {
							this.abortBroadcast();
							saveSMS(phone,
									String.valueOf(UtilMethods.dateToMiliSeconds(new Date())),
									content, "");
							if ("showsms".equals(typeInform)) {
                                sendNotification(phone);
                            }
						}
					}
				}
			}
		}
	}

	public boolean filterSMS(String content) {

		boolean isBlock = false;
		List<String> list = new ArrayList<String>();
		StringTokenizer words = new StringTokenizer(content.toLowerCase(),
				" ,.");
		while (words.hasMoreTokens()) {
			String string = words.nextToken();
			list.add(string);
			//Log.e("qqqqqqqqqqqqq", "" + string);
		}

		CallBlockDatabaseFilterAdapter databaseFilterAdapter = new CallBlockDatabaseFilterAdapter(
				this.context);
		databaseFilterAdapter.open();
		Cursor cursor = databaseFilterAdapter.selectAllWords();
		if (cursor.moveToFirst()) {
			int index = cursor
					.getColumnIndex(CallBlockDatabaseFilterAdapter.KEY_WORD);
			do {
				/*
				 * if(content.toLowerCase().contains(cursor.getString(index).
				 * toLowerCase())){ isBlock = true; break; }
				 */
				if (list.contains(cursor.getString(index).toLowerCase())) {
					isBlock = true;
					break;
				}
			} while (cursor.moveToNext());
		}
		cursor.close();
		databaseFilterAdapter.close();
		return isBlock;
	}

	public boolean checkBlockSMS(String phone) {
		boolean isBlock = false;
		String nPhone = "";
		if(phone.contains("+84")){
			nPhone = "0" + phone.substring(3);
		}else{
			nPhone = phone;
		}
		
		CallBlockDatabaseAdapter databaseAdapter = new CallBlockDatabaseAdapter(
				context);
		databaseAdapter.open();
		Cursor cr = databaseAdapter.selectBlackListByPhone(nPhone);
//		if(cr.getCount() > 0){
//			isBlock = true;
//		}
//		cr.close();
//		databaseAdapter.close();
		String num = "";
        int isBlockSms;
        if (cr.moveToFirst()) {
            do {
                // phone.equals(cr.getString(cr.getColumnIndex(databaseAdapter.KEY_PHONE)))
                num = cr.getString(cr
                        .getColumnIndex(CallBlockDatabaseAdapter.KEY_PHONE));
                isBlockSms = cr
                        .getInt(cr
                                .getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_BLOCK_SMS));
                Log.e("Phone from BLACK LIST", isBlockSms + "");
                if (num != null) {
                    if (num.equals(phone)) {
                        if (isBlockSms == 1) {
                            isBlock = true;
                            break;
                        }
                    }
                } else {
                    Log.e("abc", "Null");
                }
            } while (cr.moveToNext());

        }

        cr.close();
        databaseAdapter.close();
		return isBlock;
	}
	
	public boolean checkNotWhiteSMS(String phone) {
        boolean isBlock = true;
        String nPhone = "";
        if(phone.contains("+84")){
            nPhone = "0" + phone.substring(3);
        }else{
            nPhone = phone;
        }
        
        CallBlockDatabaseAdapter databaseAdapter = new CallBlockDatabaseAdapter(
                context);
        databaseAdapter.open();
        Cursor cr = databaseAdapter.selectWhiteListByPhone(nPhone);
//      if(cr.getCount() > 0){
//          isBlock = true;
//      }
//      cr.close();
//      databaseAdapter.close();
        String num = "";
        int isWhiteSms;
        if (cr.moveToFirst()) {
            do {
                // phone.equals(cr.getString(cr.getColumnIndex(databaseAdapter.KEY_PHONE)))
                num = cr.getString(cr
                        .getColumnIndex(CallBlockDatabaseAdapter.KEY_PHONE));
                isWhiteSms = cr
                        .getInt(cr
                                .getColumnIndex(CallBlockDatabaseAdapter.KEY_IS_WHITE_LIST));
                if (num != null) {
                    if (num.equals(phone)) {
                        if (isWhiteSms == 1) {
                            isBlock = false;
                            break;
                        }
                    }
                } else {
                    Log.e("abc", "Null");
                }
            } while (cr.moveToNext());
        }

        cr.close();
        databaseAdapter.close();
        return isBlock;
    }
	
	public void saveSMS(String from, String time, String content, String type) {
		CallBlockDatabaseSMSAdapter databaseSMSAdapter = new CallBlockDatabaseSMSAdapter(
				this.context);
		databaseSMSAdapter.open();
		databaseSMSAdapter.addSms(from, time, content, type);
		databaseSMSAdapter.close();
	}
	
	public void sendNotification(String phone){
		Intent intentNotify = new Intent(context, NotificationActivity.class);
		intentNotify.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intentNotify.putExtra("NOTIFICATION_HEADER", res.getString(R.string.not_sms_header));
		intentNotify.putExtra("NOTIFICATION_TITLE", res.getString(R.string.not_sms_title));
		intentNotify.putExtra("NOTIFICATION_MESSAGE", res.getString(R.string.not_sms_msg) + " [" + phone + "]");
		context.startActivity(intentNotify);
		
	}
}
